<template>
  <div class="app-container">
    <div v-if="!open">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商家id" prop="businessId">
        <el-input
          v-model="queryParams.businessId"
          placeholder="请输入商家id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入门店名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店电话" prop="storePhone">
        <el-input
          v-model="queryParams.storePhone"
          placeholder="请输入门店电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人姓名" prop="storeHeadName">
        <el-input
          v-model="queryParams.storeHeadName"
          placeholder="请输入负责人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人电话" prop="storeHeadPhone">
        <el-input
          v-model="queryParams.storeHeadPhone"
          placeholder="请输入负责人电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店地区" prop="storeAddress">
        <el-input
          v-model="queryParams.storeAddress"
          placeholder="请输入门店地区"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="storeLocation">
        <el-input
          v-model="queryParams.storeLocation"
          placeholder="请输入详细地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店状态" prop="storeStatus">
        <el-select v-model="queryParams.storeStatus" placeholder="请选择门店状态" clearable>
          <el-option
            v-for="dict in smkt_store_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeUpdateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['store:store:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['store:store:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['store:store:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['store:store:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" @selection-change="handleSelectionChange" v-if="!open">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="门店id" align="center" prop="id" />
      <el-table-column label="门店名称" align="center" prop="storeName" />
      <el-table-column label="门店电话" align="center" prop="storePhone" />
      <el-table-column label="负责人姓名" align="center" prop="storeHeadName" />
      <el-table-column label="负责人电话" align="center" prop="storeHeadPhone" />
      <el-table-column label="门店地区" align="center" prop="storeAddress" />
      <el-table-column label="详细地址" align="center" prop="storeLocation" />
      <el-table-column label="门店logo" align="center" prop="storeLogo" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.storeLogo" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="门店简介" align="center" prop="storeIntroduction" />
      <el-table-column label="营业时间" align="center" prop="tradeTime" />
      <el-table-column label="门店状态" align="center" prop="storeStatus">
        <template #default="scope">
          <dict-tag :options="smkt_store_status" :value="scope.row.storeStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['store:store:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['store:store:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total > 0 && !open"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    </div>
    <!-- 添加或修改店铺对话框 -->
    <!-- 平铺表单区域 -->
    <div v-if="open" class="form-container">
      <h3>{{title}}</h3>
      <el-form ref="storeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="门店名称" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入门店名称" />
        </el-form-item>
        <el-form-item label="门店电话" prop="storePhone">
          <el-input v-model="form.storePhone" placeholder="请输入门店电话" />
        </el-form-item>
        <el-form-item label="负责人姓名" prop="storeHeadName">
          <el-input v-model="form.storeHeadName" placeholder="请输入负责人姓名" />
        </el-form-item>
        <el-form-item label="负责人电话" prop="storeHeadPhone">
          <el-input v-model="form.storeHeadPhone" placeholder="请输入负责人电话" />
        </el-form-item>
        <el-form-item label="门店地区" prop="storeAddress">
          <el-cascader
              :options="addrOptions"
              v-model="marketingActivitySearchForm.activityPlace"
              placeholder="请选择省/市/区"
              @change='handleChange'
              clearable
              style="width:100%" />
        </el-form-item>
        <el-form-item label="详细地址" prop="storeLocation">
          <el-input v-model="form.storeLocation" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item>
          <div id="map" style="width: 60%; height: 400px;"></div>
        </el-form-item>
        <el-form-item label="门店图片id" prop="storeImagesId">
          <image-upload v-model="form.storeImagesId"/>
        </el-form-item>
        <el-form-item label="门店logo" prop="storeLogo">
          <image-upload v-model="form.storeLogo"/>
        </el-form-item>
        <el-form-item label="门店简介" prop="storeIntroduction">
          <el-input v-model="form.storeIntroduction"
                    placeholder="请输入门店简介"
                    :autosize="{ minRows: 3, maxRows: 10 }"
                    type="textarea"
                    resize="both"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-select v-model="form.sort">
            <el-option label="升序" value="asc" />
            <el-option label="降序" value="desc" />
          </el-select>
        </el-form-item>
        <el-form-item label="营业时间" prop="tradeTime">
          <el-input v-model="form.tradeTime" placeholder="请输入营业时间" />
        </el-form-item>
        <el-form-item label="门店状态" prop="storeStatus">
          <el-radio-group v-model="form.storeStatus">
            <el-radio
              v-for="dict in smkt_store_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
    </div>
  </div>
</template>

<script setup name="Store">
import { listStore, getStore, delStore, addStore, updateStore } from "@/api/store/store";
import { ref } from 'vue';
import { regionData, codeToText } from "element-china-area-data"
const addrOptions = ref(regionData)
const areaName = ref('') // 单独维护名称
const marketingActivitySearchForm = ref({
  activityPlace: []
})
const handleChange = (value) => {
  marketingActivitySearchForm.value.activityPlace = value
  // 添加类型转换和安全校验
  areaName.value = value
      .map(code => codeToText[String(code)] || '未知地区') // 转换为字符串查询
      .filter(Boolean) // 过滤空值
      .join('/')
  console.log(areaName.value)
}
const marker = ref(null); // 用于保存地图标记
const { proxy } = getCurrentInstance();
const { smkt_store_status } = proxy.useDict('smkt_store_status');

const storeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const daterangeUpdateTime = ref([]);
var map;

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    businessId: null,
    storeName: null,
    storePhone: null,
    storeHeadName: null,
    storeHeadPhone: null,
    storeAddress: null,
    storeLocation: null,
    storeStatus: null,
    createTime: null,
    updateTime: null
  },
  rules: {
    businessId: [
      { required: true, message: "商家id不能为空", trigger: "blur" }
    ],
    storeName: [
      { required: true, message: "门店名称不能为空", trigger: "blur" }
    ],
    storePhone: [
      { required: true, message: "门店电话不能为空", trigger: "blur" }
    ],
    storeHeadName: [
      { required: true, message: "负责人姓名不能为空", trigger: "blur" }
    ],
    storeHeadPhone: [
      { required: true, message: "负责人电话不能为空", trigger: "blur" }
    ],
    storeAddress: [
      { required: true, message: "门店地区不能为空", trigger: "blur" }
    ],
    storeLocation: [
      { required: true, message: "详细地址不能为空", trigger: "blur" }
    ],
    storeImagesId: [
      { required: true, message: "门店图片id不能为空", trigger: "blur" }
    ],
    storeLogo: [
      { required: true, message: "门店logo不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
const markerRef = ref(null); // 保存水滴标记
/** 查询店铺列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  if (null != daterangeUpdateTime && '' != daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  listStore(queryParams.value).then(response => {
    storeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    businessId: null,
    storeName: null,
    storePhone: null,
    storeHeadName: null,
    storeHeadPhone: null,
    storeAddress: null,
    storeLocation: null,
    storeLongitude: null,
    storeLatitude: null,
    storeImagesId: null,
    storeLogo: null,
    storeIntroduction: null,
    sort: null,
    tradeTime: null,
    storeStatus: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("storeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  daterangeUpdateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加店铺";
  //1.表示DOM更新完毕后立即执行的方法,因为我们要确保上方的地图容器div已创建,才能往div里装地图
  nextTick(() => {
    if (!map) {
      map = new BMapGL.Map("map");
      let point = new BMapGL.Point(116.4074, 39.9024);
      map.centerAndZoom(point, 15);
      map.enableScrollWheelZoom(true);
      // 监听点击地图事件
      map.addEventListener("click", function (e) {
        const longitude = e.point.lng.toFixed(6);
        const latitude = e.point.lat.toFixed(6);
        // 将经纬度以“经度,纬度”的格式赋值给 storeLocation 输入框
        form.value.storeLocation = `${longitude},${latitude}`;
        // 设置水滴图标
        const icon = new BMapGL.Icon("/images/waterMap.png", new BMapGL.Size(32, 32), {
          anchor: new BMapGL.Size(16, 32), // 图标锚点（中心点）
          imageSize: new BMapGL.Size(32, 32)
        });

        // 创建标记
        const marker = new BMapGL.Marker(e.point, { icon: icon });
        map.addOverlay(marker);

        // 如果之前已有标记，则移除旧的
        if (markerRef.value) {
          map.removeOverlay(markerRef.value);
        }
        markerRef.value = marker;
      });
    }

    // 添加 null 判断避免报错
    const loader = document.getElementById("loader-wrapper");
    if (loader) {
      loader.style.display = "none";
    }
  });

}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getStore(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改店铺";

    nextTick(() => {
      if (form.value.storeLongitude && form.value.storeLatitude) {
        const lng = parseFloat(form.value.storeLongitude);
        const lat = parseFloat(form.value.storeLatitude);
        const point = new BMapGL.Point(lng, lat);

        map.centerAndZoom(point, 15);

        // 显示水滴图标
        const icon = new BMapGL.Icon("/images/waterMap.png", new BMapGL.Size(32, 32), {
          anchor: new BMapGL.Size(16, 32),
          imageSize: new BMapGL.Size(32, 32)
        });

        const marker = new BMapGL.Marker(point, { icon: icon });
        map.addOverlay(marker);

        if (markerRef.value) {
          map.removeOverlay(markerRef.value);
        }
        markerRef.value = marker;
      }
    });


  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["storeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateStore(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addStore(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除店铺编号为"' + _ids + '"的数据项？').then(function() {
    return delStore(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('store/store/export', {
    ...queryParams.value
  }, `store_${new Date().getTime()}.xlsx`)
}

getList();

</script>

